#coding:utf-8
import os
import hashlib
import jwt
from datetime import datetime, timedelta
from flask import Flask, request, make_response, render_template, redirect, url_for, send_from_directory
from addMark import addWaterMarking
from testMark import testWaterMarking

UPLOAD_FOLDER='home'
ALLOWED_EXTENSIONS=set(['png','jpg','jpeg','gif'])

app=Flask(__name__)
global strMark
strMark = ' '
app.config['UPLOAD_FOLDER']=UPLOAD_FOLDER

# 随机的高强度密钥
app.secret_key = 'vN8Tq6grBKAl9ZOh6i71Or6'
password_file = './data/password'
default_pw = 'admin'
default_user = 'admin'

# token 90天后过期
max_age = 90 * 24 * 60 * 60  # 90天 * 24小时 * 60分钟 * 60秒

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.',1)[1] in ALLOWED_EXTENSIONS

@app.route('/login', methods=['GET', 'POST'])
def login():
    # 如果文件不存在则创建默认密码文件
    if not os.path.exists(password_file):
        os.makedirs(os.path.dirname(password_file), exist_ok=True)
        with open(password_file, 'w') as f:
            f.write(default_pw)

    # 读取密码文件
    with open(password_file) as f:
        default_password = f.read().strip()

    # 生成密码的哈希值
    hashed_password = hashlib.sha256(default_password.encode("utf-8")).hexdigest()
    hashed_user = hashlib.sha256(default_user.encode("utf-8")).hexdigest()

    if request.method == 'POST':
        # 从表单中获取账号密码
        hashed_password = request.form['hash']
        # 验证密码的正确性
        if hashed_password == hashed_password and hashed_user == hashed_user:
            # 如果账号密码验证通过
            token = generate_token()
            # 生成一个令牌
            resp = make_response(redirect(url_for('upload_file')))
            # 创建一个重定向响应对象，跳转到相册页面
            resp.set_cookie('token', token, max_age=max_age)
            # 设置cookie，保存令牌，设置过期时间为max_age
            return resp
            # 返回响应对象
        else:
            # 如果密码验证不通过
            return render_template('login.html', error='密码输入错误！')
            # 返回登录页面模板，并传递错误信息
    return render_template('login.html')
    # 返回登录页面模板

@app.route('/logout')
def logout():
    # 生成一个响应对象并重定向到登录页面
    resp = make_response(redirect(url_for('login')))
    # 设置一个名为'token'的cookie，过期时间为0
    resp.set_cookie('token', '', expires=0)
    # 返回响应对象
    return resp

@app.route('/',methods=['GET','POST'])
def upload_file():
    token = request.cookies.get('token')
    if not validate_token(token):
        return redirect(url_for('login'))

    if request.method=='POST':
        file1=request.files['file']
        file2=request.files['file_mask']
        if file1 and allowed_file(file1.filename) and file2 and allowed_file(file2.filename):
            addWaterMarking(file1,file2)
            return redirect(url_for('upload_file'))
    return '''
    <!DOCTYPE html>
    <html>
    <head>
        <title>Upload New File</title>
        <style>
            body {
                font-family: Arial, sans-serif;
                margin: 0;
                padding: 0;
                background-color: #f0f0f0;
            }
            .container {
                position: relative;  
                width: 80%;
                margin: 0 auto;
                padding: 20px;
                box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
                background-color: #fff;
                border-radius: 5px;
            }
            h1, h2 {
                color: #333;
            }
            input[type="file"] {
                margin: 10px 0;
                padding: 10px;
                border: 1px solid #ddd;
                border-radius: 5px;
            }
            input[type="submit"], .logout-button {  
                background-color: #007BFF;
                color: white;
                padding: 10px 20px;
                border: none;
                border-radius: 4px;
                cursor: pointer;
                transition: background-color 0.3s ease;
            }
            input[type="submit"]:hover, .logout-button:hover {  
                background-color: #0056b3;
            }
            a {
                color: #007BFF;
                text-decoration: none;
            }
            a:hover {
                text-decoration: underline;
            }
            .logout-button {  
                position: absolute;
                top: 20px;
                right: 20px;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <a class="btn btn-primary me-2 logout-button" href="/logout" style="color: white; background-color: #007BFF; border-color: #007BFF;">登出</a>  <!-- 修改这一行 -->
            <h1>添加/提取水印的系统</h1>
            <h2>选择要添加水印的图片</h2>
            <form action="/" method="POST" enctype="multipart/form-data">
                <input type="file" name="file" />
                <h2>选择水印</h2>
                <input type="file" name="file_mask" />
                <p>
                    <input type="submit" value="Handle" />
                </p>
            </form>
            <a href="test">Test Watermarking</a>
            <p>
                <script type="text/javascript">  
                    document.write("<img src='../static/output.png?v="+new Date().getTime()+"'>");   
                </script>  
            </p>
        </div>
    </body>
    </html>
    '''

@app.route('/test',methods=['GET','POST'])
def test_file():
    token = request.cookies.get('token')
    if not validate_token(token):
        return redirect(url_for('login'))

    global strMark
    if request.method=='POST':
        file1=request.files['file']
        file2=request.files['file_mask']
        if file1 and allowed_file(file1.filename) and file2 and allowed_file(file2.filename):
            boolMark = testWaterMarking(file1,file2)
            if boolMark == False:
                strMark = 'False'
            else:
                strMark = 'True'
        else:
            # 如果没有file2，执行提取图片的操作
            testWaterMarking(file1)
        return redirect(url_for('test_file'))
    return '''
<!DOCTYPE html>
<html>
<head>
    <title>Upload New File</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f0f0f0;
        }
        .container {
            position: relative;
            width: 80%;
            margin: 0 auto;
            padding: 20px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            background-color: #fff;
            border-radius: 5px;
        }
        h1, h2 {
            color: #333;
        }
        input[type="file"] {
            margin: 10px 0;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        input[type="submit"], .logout-button {
            background-color: #007BFF;  
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        input[type="submit"]:hover, .logout-button:hover {
            background-color: #0056b3;  
        }
        a {
            color: #007BFF;  
            text-decoration: none;
        }
        a:hover {
            text-decoration: underline;
        }
        .logout-button {
            position: absolute;
            top: 20px;
            right: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <a class="btn btn-primary me-2 logout-button" href="/logout" style="color: white; background-color: #007BFF; border-color: #007BFF;">登出</a>  <!-- 修改这一行 -->
        <h1>添加/提取水印系统g</h1>
        <h2>选择要添加水印的图片</h2>
        <form action="/test" method="POST" enctype="multipart/form-data">
            <input type="file" name="file" />
            <h2>选择要水印</h2>
            <input type="file" name="file_mask" />
            <p>
                <input type="submit" value="Handle" />
            </p>
        </form>
        <a href="/">Add Watermarking</a>
        <p>
            ''' + strMark+  '''
        </p>
        <p>
            <script type="text/javascript">  
                document.write("<img src='../static/extracted_watermark.png?v="+new Date().getTime()+"' alt='Extracted Watermark'>");   
            </script>  
        </p>
    </div>
</body>
</html>
'''

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'],filename)

def generate_token():
    # 获取当前时间加上90天
    expiration = datetime.utcnow() + timedelta(days=90)
    # 定义一个字典，包含一个键值对，键为'exp'，值为expiration
    data = {
        'exp': expiration
    }

    # 使用jwt.encode()函数将data字典进行编码，使用app.secret_key作为密钥，algorithm参数指定加密算法为'HS256'
    token = jwt.encode(data, app.secret_key, algorithm='HS256')

    # 返回编码后的token
    return token

def validate_token(token):
    try:
        # 尝试解码token
        data = jwt.decode(token, app.secret_key, algorithms=['HS256'])
        # 获取token的过期时间
        expired_date = data.get('exp')
        # 如果过期时间不存在，则返回False
        if expired_date is None:
            return False
        # 将过期时间转换为时间戳
        print_date = datetime.fromtimestamp(expired_date)
        # 将过期时间格式化为指定格式的字符串
        print(print_date.strftime('%Y-%m-%d %H:%M:%S'))
        # 返回True表示token有效
        return True
    # 如果token已过期，执行以下代码
    except jwt.ExpiredSignatureError:
        # 返回False表示token无效
        return False
    # 如果token无效，执行以下代码
    except jwt.InvalidTokenError:
        # 返回False表示token无效
        return False

if __name__ == '__main__':
    strMark = ''
    app.run(port=2020, host="192.168.1.76", debug=True)